<template>
  <tl-sub-page :render="render" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" :append-to-body="true" class="tl-dialog" width="1200px" @open="open" @close="close">
    <el-row v-if="fromApproval === '1'">
      <el-col :span="24">
        <el-button type="danger" style="float: right" size="small" icon="el-icon-close" circle @click="doCancelEdit"></el-button>
      </el-col>
    </el-row>
    <br />
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
      <el-row>
        <el-col :span="12">
          <el-form-item label="离职/转岗人员" prop="oldprojectmanager" :rules="rules.validateRequire">
            <tl-ref-user v-model="model.oldprojectmanagercode" :initDisplayData.sync="model.oldprojectmanager" :singleSelect="true" dataType="code" :filterDimission="false" @confirm="confirm" :disabled="disableEditSubmit || disableSave"></tl-ref-user>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="离职/转岗人员工号" prop="oldprojectmanagercode" :rules="rules.validateRequire">
            <el-input v-model="model.oldprojectmanagercode" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <div style="margin-left: 20px">
        <mpm-project-info-index ref="managerInfo" :model="model" :disabled="disableEditSubmit || disableSave"></mpm-project-info-index>
      </div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="申请人姓名" prop="username">
            <el-input v-model="model.username" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申请人工号" prop="usercode">
            <el-input v-model="model.usercode" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="提交日期" prop="submitdate">
            <el-date-picker v-model="model.submitdate" type="date" placeholder="提交日期" value-format="yyyy-MM-dd" :disabled="true"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <tl-approval-history ref="history" sourceType="MpmProjectChangeManager" :sourceId="model.id" />
    <mpm-index-edit ref="mpmIndexEdit" :lastid="model.id"></mpm-index-edit>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="showHistoryIndex" v-if="showHistory">历史交接</el-button>
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading || submitLoading" v-if="!disableEditSubmit" :disabled="disableSave"><svg-icon icon-class="save" />保存</el-button>
      <el-button type="primary" @click="projectSubmit" :loading="saveLoading || submitLoading" v-if="!disableEditSubmit" :disabled="!(stateAdd || stateEdit)"><svg-icon icon-class="send" />提交审批</el-button>
      <tl-attachment sourceType="MpmProjectChangeManager" :sourceId="model.id" :disabled="disableAttachment" :editable="stateEdit"></tl-attachment>
      <el-button type="primary" @click="$refs.history.visible = true" :disabled="disableApprovalHistory"><svg-icon icon-class="list" />审批历史</el-button>
    </div>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit_edit } from '@/mixins/mixin_approval_edit'
import { validateNull } from '@tapui/utils/validate'
/** 子组件 */
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import mpmProjectInfoIndex from '../mpmProjectChangeManagerInfo/indexComp'
import mpmIndexEdit from './indexEdit'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit_edit],
  components: { mpmProjectInfoIndex, mpmIndexEdit },
  data() {
    return {
      moduleTitle: '离职/转岗人员工作交接',
      urlPrefix: '/mpm/projectChangeManager/',
      url: {
        queryProjectCodeAndName: '/mpm/projectChangeManager/queryProjectCodeAndName'
        // 额外的url
      },
      projectmodel: '',
      fromApproval: ''
    }
  },
  props: {
    showHistory: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    assignDefaultValue() {
      if (this.isAdd) {
        if (this.codeModel.flowidList && this.codeModel.flowidList.length > 0) {
          this.$set(this.model, 'flowid', parseInt(this.codeModel.flowidList[0].id))
        }
        this.$set(this.model, 'orgcode', this.org.code)
        this.$set(this.model, 'orgname', this.org.name)
        this.$set(this.model, 'deptcode', this.dept.code)
        this.$set(this.model, 'deptname', this.dept.fullname)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        this.$set(this.model, 'submitdate', new Date())
      }
    },
    loaded() {
      // 页面加载完毕执行
      if (!this.isAdd && this.model.docno) {
        this.title = this.title + `（单据编号：${this.model.docno}）`
      }
      // 获取需变更项目信息
      this.$refs.managerInfo.doQuery()
    },
    doCancelEdit() {
      this.visible = false
      this.$emit('close')
      this.$emit('refresh')
    },
    close() {
      this.$refs.managerInfo.datas = []
    },
    confirm() {
      let data = this.model.oldprojectmanagercode
      if (data !== null && data !== undefined && data !== '') {
        const param = { projectmanagercode: data, usercode: this.user.code }
        getAction(this.url.queryProjectCodeAndName, param).then((res) => {
          if (res.success) {
            this.$set(this.$refs.managerInfo, 'datas', res.result)
          } else {
            this.$set(this.model, 'oldprojectmanagercode', null)
            this.$set(this.model, 'oldprojectmanager', null)
            this.$tap.alert(res.message, 'warning')
          }
        })
      }
    },
    async doSubmitEdit() {
      if (!this.beforeSubmit()) {
        return
      }
      if (this.isAdd) {
        this.doAdd()
      } else {
        this.doEdit()
      }
    },
    async projectSubmit() {
      let that = this
      that.$refs.form.validate(async (valid, res) => {
        if (valid) {
          let saveresult = await that.addBase()
          if (saveresult) {
            let approvalResult = await that.beforeApproval()
            if (!approvalResult) {
              this.submitLoading = false
              this.saveLoading = false
              return
            }
            that.submitLoading = true
            that.saveLoading = true
            putAction(that.url.submit, that.model)
              .then((res) => {
                if (res.success) {
                  that.queryData(that.model.id).then((_) => {
                    that.loaded()
                    that.saveLoading = false
                    that.submitLoading = false
                  })
                  that.$tap.alert('提交审批成功', 'success')
                } else {
                  that.$tap.alert(res.message, 'warning')
                  that.saveLoading = false
                  that.submitLoading = false
                }
              })
              .catch((err) => {
                that.saveLoading = false
                that.submitLoading = false
              })
          }
        } else {
          that.saveLoading = false
          that.submitLoading = false
          that.$tap.alert('按要求填写表单数据项，包括必填项，数据格式等')
        }
      })
    },
    beforeSubmit() {
      if (this.$refs.managerInfo.datas.length === 0) {
        this.$tap.alert('该员工不存在待交接项目！')
        return false
      }
      this.$set(this.model, 'managerinfo', this.$refs.managerInfo.datas)
      return true
    },
    beforeApproval() {
      for (let item of this.$refs.managerInfo.datas) {
        if (validateNull(item.newusercode)) {
          this.$tap.alert('交接人请填写完整！')
          return false
        }
      }
      return true
    },
    showHistoryIndex() {
      this.$refs.mpmIndexEdit.visible = true
    }
  },
  watch: {
    codeModel(newVal, oldVal) {
      this.$set(this.model, 'flowid', parseInt(this.codeModel.flowidList[0].id))
    }
  }
}
</script>
